package com.competition.bonusrule.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.competition.bonusrule.domain.vo.BonusruleVo;
import com.competition.common.core.domain.entity.SysDictData;
import com.competition.common.exception.ServiceException;
import com.competition.common.utils.SecurityUtils;
import com.competition.common.utils.StringUtils;
import com.competition.common.utils.bean.BeanValidators;
import com.competition.system.service.ISysDictDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.competition.bonusrule.mapper.BonusruleMapper;
import com.competition.bonusrule.domain.Bonusrule;
import com.competition.bonusrule.service.IBonusruleService;

import javax.validation.Validator;

/**
 * 奖金规则Service业务层处理
 * 
 * @author cui
 * @date 2025-01-21
 */
@Service
public class BonusruleServiceImpl implements IBonusruleService
{
    private static final Logger log = LoggerFactory.getLogger(BonusruleServiceImpl.class);
    @Autowired
    protected Validator validator;

    @Autowired
    private BonusruleMapper bonusruleMapper;

    @Autowired
    ISysDictDataService dictDataService;

    private static final String NUMERIC_REGEX = "^\\d+$";

    /**
     * 查询奖金规则
     * 
     * @param ruleId 奖金规则主键
     * @return 奖金规则
     */
    @Override
    public Bonusrule selectBonusruleByRuleId(Long ruleId)
    {
        return bonusruleMapper.selectBonusruleByRuleId(ruleId);
    }

    /**
     * 查询奖金规则列表
     * 
     * @param bonusrule 奖金规则
     * @return 奖金规则
     */
    @Override
    public List<Bonusrule> selectBonusruleList(Bonusrule bonusrule)
    {
        return bonusruleMapper.selectBonusruleList(bonusrule);
    }

    /**
     * 新增奖金规则
     * 
     * @param bonusrule 奖金规则
     * @return 结果
     */
    @Override
    public int insertBonusrule(Bonusrule bonusrule)
    {
        return bonusruleMapper.insertBonusrule(bonusrule);
    }

    /**
     * 修改奖金规则
     * 
     * @param bonusrule 奖金规则
     * @return 结果
     */
    @Override
    public int updateBonusrule(Bonusrule bonusrule)
    {
        return bonusruleMapper.updateBonusrule(bonusrule);
    }

    /**
     * 批量删除奖金规则
     * 
     * @param ruleIds 需要删除的奖金规则主键
     * @return 结果
     */
    @Override
    public int deleteBonusruleByRuleIds(Long[] ruleIds)
    {
        return bonusruleMapper.deleteBonusruleByRuleIds(ruleIds);
    }

    /**
     * 删除奖金规则信息
     * 
     * @param ruleId 奖金规则主键
     * @return 结果
     */
    @Override
    public int deleteBonusruleByRuleId(Long ruleId)
    {
        return bonusruleMapper.deleteBonusruleByRuleId(ruleId);
    }

    @Override
    public List<BonusruleVo> selectBonusruleVoList(BonusruleVo bonusrule) {
        return bonusruleMapper.selectBonusruleVoList(bonusrule);
    }

//    public long validateDictData(String dictLabel, StringBuilder failureMsg, int failureNum) {
//        SysDictData dictData = new SysDictData();
//        dictData.setDictLabel(dictLabel);
//        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
//        if (list.size() == 0) {
//            failureNum++;
//            String msg = "<br/>" + failureNum + " 导入失败：";
//            failureMsg.append(msg + "数据错误");
//            return 0;
//        }else{
//            return list.get(0).getDictCode();
//        }
//    }

    /**
     * 导入用户数据
     *
     * @param list 奖金数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importRules(List<BonusruleVo> list, boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(list) || list.size() == 0)
        {
            throw new ServiceException("导入奖金规则数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (BonusruleVo rule : list)
        {
            try
            {
                // 验证是否存在这个规则
                List<BonusruleVo> list1 = bonusruleMapper.selectBonusruleVoList(rule);
                if (list1.size() == 0)
                {
                    BeanValidators.validateWithException(validator, rule);
                    //验证数据字典是否正确
//                    long competitionType = dictDataService.validateDictData(rule.getCompetitionTypeName(), failureMsg, failureNum);
//                    if (competitionType==0) {  continue; }
//                    else {rule.setCompetitionType(competitionType);}
//
//                    long competitionGrade = dictDataService.validateDictData(rule.getCompetitionGradeName(), failureMsg, failureNum);
//                    if (competitionGrade==0) {  continue; }
//                    else {rule.setCompetitionGrade(competitionGrade);}
//
//                    long awardGrade = dictDataService.validateDictData(rule.getAwardGradeName(), failureMsg, failureNum);
//                    if (awardGrade==0) {  continue; }
//                    else {rule.setAwardGrade(awardGrade);}
//
//                    long teamType = dictDataService.validateDictData(rule.getTeamTypeName(), failureMsg, failureNum);
//                    if (teamType==0) {  continue; }
//                    else {rule.setTeamType(teamType);}
                    rule.setCreateBy(operName);
                    bonusruleMapper.insertBonusrule(rule);
                    successNum++;

                }
                else if (isUpdateSupport)
                {
//                    BeanValidators.validateWithException(validator, user);
//                    checkUserAllowed(u);
//                    checkUserDataScope(u.getUserId());
//                    deptService.checkDeptDataScope(user.getDeptId());
//                    user.setUserId(u.getUserId());
//                    user.setUpdateBy(operName);
//                    userMapper.updateUser(user);
//                    successNum++;
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum +  " 导入失败：" + " "
                            + rule.getCompetitionTypeName() + " "
                            + rule.getCompetitionGradeName()
                            + "对应的奖金规则已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum +  " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if(failureNum == 0){
            return successMsg.toString();
        }else {
            return failureMsg.toString();
        }
    }

    // 在你现有的 BonusruleServiceImpl 类中添加这些方法

    @Override
    public List<BonusruleVo> selectBonusDistributionList(BonusruleVo bonusruleVo)
    {
        List<BonusruleVo> list = bonusruleMapper.selectBonusDistributionList(bonusruleVo);

        // 为每个记录检查当前用户是否有分配权限
        Long currentUserId = SecurityUtils.getUserId();
        for (BonusruleVo vo : list) {
            vo.setHasPermission(this.checkDistributionPermission(vo.getAwardId(), currentUserId));
        }

        return list;
    }

    @Override
    public BonusruleVo matchBonusRule(Long awardId)
    {
        BonusruleVo awardInfo = bonusruleMapper.selectAwardInfoForDistribution(awardId);
        if (awardInfo != null) {
            // 匹配奖金规则
            Bonusrule queryRule = new Bonusrule();
            queryRule.setCompetitionType(awardInfo.getCompetitionType());
            queryRule.setCompetitionGrade(awardInfo.getCompetitionGrade());
            queryRule.setAwardGrade(awardInfo.getAwardGrade());
            queryRule.setTeamType(awardInfo.getTeamType());

            List<Bonusrule> matchedRules = bonusruleMapper.selectBonusruleList(queryRule);
            if (!matchedRules.isEmpty()) {
                Bonusrule matchedRule = matchedRules.get(0);
                awardInfo.setMatchedAmount(matchedRule.getAmount().intValue());
                awardInfo.setRuleId(matchedRule.getRuleId());
            }

            // 获取团队成员信息
            List<BonusruleVo.TeamMember> teamMembers = this.getTeamMembers(awardInfo.getTeamId());
            awardInfo.setTeamMembers(teamMembers);

            // 计算分配统计
            this.calculateDistributionStats(awardInfo);

            // 检查权限
            Long currentUserId = SecurityUtils.getUserId();
            awardInfo.setHasPermission(this.checkDistributionPermission(awardId, currentUserId));
        }

        return awardInfo;
    }

    @Override
    public int distributeBonus(BonusruleVo bonusruleVo)
    {
        // 验证分配比例
        if (!this.validateDistributionRatio(bonusruleVo.getTeamMembers(), bonusruleVo.getMatchedAmount())) {
            throw new ServiceException("分配比例验证失败，总比例必须等于1且分配金额等于总金额");
        }

        // 记录分配操作
        bonusruleVo.setDistributorId(SecurityUtils.getUserId());
        bonusruleVo.setDistributorName(SecurityUtils.getUsername());

        return bonusruleMapper.insertBonusDistribution(bonusruleVo);
    }

    @Override
    public boolean checkDistributionPermission(Long awardId, Long userId)
    {
        // 获取获奖记录对应的团队ID
        Long teamId = bonusruleMapper.selectTeamIdByAwardId(awardId);
        if (teamId == null) {
            return false;
        }

        // 获取第一指导老师
        Long firstTeacherId = this.getFirstTeacherByTeamId(teamId);

        return firstTeacherId != null && firstTeacherId.equals(userId);
    }

    @Override
    public Long getFirstTeacherByTeamId(Long teamId)
    {
        return bonusruleMapper.selectFirstTeacherByTeamId(teamId);
    }

    // 辅助方法
    private List<BonusruleVo.TeamMember> getTeamMembers(Long teamId)
    {
        // 获取指导老师
        List<BonusruleVo.TeamMember> teachers = bonusruleMapper.selectTeamTeachers(teamId);
        // 获取参赛学生
        List<BonusruleVo.TeamMember> students = bonusruleMapper.selectTeamStudents(teamId);

        List<BonusruleVo.TeamMember> allMembers = new ArrayList<>();
        allMembers.addAll(teachers);
        allMembers.addAll(students);

        return allMembers;
    }

    private void calculateDistributionStats(BonusruleVo awardInfo)
    {
        if (awardInfo.getTeamMembers() != null) {
            double distributedAmount = awardInfo.getTeamMembers().stream()
                    .mapToDouble(member -> member.getAmount() != null ? member.getAmount() : 0)
                    .sum();
            double totalRatio = awardInfo.getTeamMembers().stream()
                    .mapToDouble(member -> member.getDistributionRatio() != null ? member.getDistributionRatio() : 0)
                    .sum();

            awardInfo.setDistributedAmount(distributedAmount);
            awardInfo.setRemainingAmount(awardInfo.getMatchedAmount() - distributedAmount);
            awardInfo.setDistributionProgress(totalRatio * 100);
        }
    }

    private boolean validateDistributionRatio(List<BonusruleVo.TeamMember> teamMembers, Integer totalAmount)
    {
        if (teamMembers == null || teamMembers.isEmpty()) {
            return false;
        }

        double totalRatio = teamMembers.stream()
                .mapToDouble(member -> member.getDistributionRatio() != null ? member.getDistributionRatio() : 0)
                .sum();

        double distributedAmount = teamMembers.stream()
                .mapToDouble(member -> member.getAmount() != null ? member.getAmount() : 0)
                .sum();

        // 验证比例总和为1，且分配金额等于总金额
        return Math.abs(totalRatio - 1.0) < 0.001 && Math.abs(distributedAmount - totalAmount) < 0.01;
    }


}
